<?php
/**
 * Created by leiying
 * Date: 2018/6/7
 * Time: 17:42
 */

namespace Home\Controller;


use Think\Controller;

class AjaxController extends Controller
{
    /**获取区域下级
     * @author leiying
     */
    public function getRegion(){
        $post_type = I("post.type");
        $post_parent = I("post.parent");
        $type   = !empty($post_type)? intval($post_type)   : 0;
        $parent = !empty($post_parent) ? intval($post_parent) : 0;
        $regions = M("region")->field("code region_id,fullName region_name")->where(array("type"=>$type,"parentCode"=>$parent))->select();
        if($regions){
            $this->success($regions);
        }else{
            $this->error("区域为空");
        }
    }

    /**获取资料
     * @author leiying
     */
    public function getData(){
        if(IS_POST){
            $p_id = I('post.p_id',0);
            if($p_id){
                $res = M("data")->field("name,ext,id")->where(array('p_id'=>$p_id))->find();
                if($res){
                    $data = array(
                        'path' => U('Home/Data/download',array('id'=>$res['id'])),
                        'filename' => $res["name"].'.'.$res['ext'],
                    );
                    $this->success($data);
                }else{
                    $this->error("未上传资料");
                }
            }else{
                $this->error("请选择项目分类");
            }
        }else{
            $this->error("非法操作");
        }
    }

    /**真伪查询
     * @author leiying
     */
    public function CheckApply(){
        $post = I('post.');
        $number = isset($post["number"])?trim($post["number"]):'';
        if(empty($number)){$this->error("项目编号不能为空");}
        $check_account = isset($post["check_account"])?trim($post["check_account"]):'';
        if(empty($check_account)){$this->error("账号不能为空");}
        $check_pwd = isset($post["check_pwd"])?trim($post["check_pwd"]):'';
        if(empty($check_pwd)){$this->error("密码不能为空");}

        $row = M("apply")->where(array("number"=>$number,'check_account'=>$check_account,"check_pwd" => $check_pwd))->find();
        if($row){
            $this->success($row["id"]);
        }else{
            $this->error("项目编号或账号密码错误");
        }
    }

    /**项目查询
     * @author leiying
     */
    public function QueryProgress(){
        $post = I('post.');

        $number = isset($post["number"])?$post["number"]:'';
        if(empty($number)){$this->error("项目编号不能为空");}

        $validate_phone = trim($post["validate_phone"]);
        if(empty($validate_phone)){
            $this->error("请输入手机号码");
        }else{
            if(!$this->check_phone($validate_phone)){
                $this->error("手机号码有误，请重填");
            }
        }
        $validate_code = trim($post["validate_code"]);
        /*验证短信*/
        $res_record = M("validate_record")->where(array("record_key"=>$validate_phone,"record_type"=>'query_progress'))->getField("record_code");

        if(!empty($res_record)){
            if($res_record != $validate_code){
                $this->error("短信验证码不正确");
            }
        }else{
            $this->error("验证码信息不存在");
        }


        $row = M("apply")->where(array("number"=>$number,'validate_phone'=>$validate_phone))->find();
        if($row){
            $this->success($row["id"]);
        }else{
            $this->error("项目编号或验证手机号码错误");
        }

    }

    /**提交申请
     * @author leiying
     */
    public function ApplyAdd(){

        $post = I('post.');
        $validate_phone = trim($post["validate_phone"]);
        if(empty($validate_phone)){
            $this->error("请输入手机号码");
        }else{
            if(!$this->check_phone($validate_phone)){
                $this->error("手机号码有误，请重填");
            }
        }
        $validate_code = trim($post["validate_code"]);
        /*验证短信*/
        $res_record = M("validate_record")->where(array("record_key"=>$validate_phone,"record_type"=>'send_apply'))->getField("record_code");

        if(!empty($res_record)){
            if($res_record != $validate_code){
                $this->error("短信验证码不正确");
            }
        }else{
            $this->error("验证码信息不存在");
        }

        $p_id = isset($post['p_id'])?$post['p_id']:0;
        if(empty($p_id)){$this->error("请选择项目");}

        $apply_name = isset($post['apply_name'])?$post['apply_name']:'';
        if(empty($apply_name)){$this->error("请填写项目名称");}

        $is_deliver = isset($post["is_deliver"])?(int)$post["is_deliver"]:0;
        if(empty($is_deliver) || !in_array($is_deliver,array(1,2))){$this->error("请选择材料寄送");}

        $tracking_no = '';
        if($is_deliver == 1){//已经寄送
            $tracking_no = isset($post['tracking_no'])?$post['tracking_no']:'';
            if(empty($tracking_no)){$this->error("请填写快递单号");}
        }

        $company_name = isset($post['company_name'])?$post['company_name']:'';
        if(empty($company_name)){$this->error("请填写主审单位");}

        $depart_name = isset($post['depart_name'])?$post['depart_name']:'';
        if(empty($depart_name)){$this->error("请填写部门");}

        $contact = isset($post["contact"])?$post["contact"]:'';
        if(empty($contact)){$this->error("请填写联系人（主审单位）");}

        /*选填*/
        $position_name = isset($post["position_name"])?$post["position_name"]:'';

        $contact_phone = isset($post['contact_phone'])?$post['contact_phone']:'';
        if(empty($contact_phone)){$this->error("请填写电话号码（主审单位）");}

        $contact_p = isset($post['contact_p'])?$post['contact_p']:'';
        if(empty($contact_p)){$this->error("请选择省(主审单位)");}
        $contact_c = isset($post['contact_c'])?$post['contact_c']:'';
        if(empty($contact_c)){$this->error("请选择市(主审单位)");}
        $contact_d = isset($post['contact_d'])?$post['contact_d']:'';
        if(empty($contact_d)){$this->error("请选择区(主审单位)");}
        $contact_address = isset($post['contact_address'])?$post['contact_address']:'';
        if(empty($contact_address)){$this->error("请填写地址（主审单位）");}

        $region_list = array($contact_p,$contact_c,$contact_d);
        $return_address = $this->get_address($region_list);
        $contact_address = $return_address.$contact_address;

        $need_survey = isset($post['need_survey'])?(int)$post['need_survey']:0;
        if(empty($need_survey) || !in_array($need_survey,array(1,2))){$this->error("请选择是否现场踏勘");}
        $survey_time = '';
        $survey_address = '';
        $survey_contact = '';
        $survey_attention = '';
        if($need_survey == 1){
            $survey_time = isset($post['survey_time'])?$post['survey_time']:"";
            if(empty($survey_time) ){$this->error("请选择现场踏勘时间段");}
            $survey_p = isset($post['survey_p'])?$post['survey_p']:'';
            if(empty($survey_p)){$this->error("请选择省(现场踏勘)");}
            $survey_c = isset($post['survey_c'])?$post['survey_c']:'';
            if(empty($survey_c)){$this->error("请选择市(现场踏勘)");}
            $survey_d = isset($post['survey_d'])?$post['survey_d']:'';
            if(empty($survey_d)){$this->error("请选择区(现场踏勘)");}
            $survey_address = isset($post['survey_address'])?$post['survey_address']:'';
            if(empty($survey_address)){$this->error("请填写地址（现场踏勘）");}

            $region_list = array($survey_p,$survey_c,$survey_d);
            $return_address = $this->get_address($region_list);
            $survey_address = $return_address.$survey_address;

            $survey_contact = isset($post['survey_contact'])?$post['survey_contact']:'';
            if(empty($survey_contact)){$this->error("请填写联系人（现场踏勘）");}
            $survey_attention = isset($post['survey_attention'])?$post['survey_attention']:'';
            if(empty($survey_attention)){$this->error("请填写注意事项（现场踏勘）");}
        }

        $need_deliver = isset($post['need_deliver'])?(int)$post['need_deliver']:0;
        if(empty($need_deliver) || !in_array($need_deliver,array(1,2))){$this->error("请选择是否需寄送审批表格");}

        $receiver_name = '';
        $receiver_address = '';
        $receiver_phone = '';
        if($need_deliver == 1){
            $receiver_name = isset($post['receiver_name'])?$post['receiver_name']:'';
            if(empty($receiver_name)){$this->error("请填写收件人姓名");}
            $receiver_p = isset($post['receiver_p'])?$post['receiver_p']:'';
            if(empty($receiver_p)){$this->error("请选择省(寄送审批表格)");}
            $receiver_c = isset($post['receiver_c'])?$post['receiver_c']:'';
            if(empty($receiver_c)){$this->error("请选择市(寄送审批表格)");}
            $receiver_d = isset($post['receiver_d'])?$post['receiver_d']:'';
            if(empty($receiver_d)){$this->error("请选择区(寄送审批表格)");}
            $receiver_address = isset($post['receiver_address'])?$post['receiver_address']:'';
            if(empty($receiver_address)){$this->error("请填写地址（寄送审批表格）");}

            $region_list = array($receiver_p,$receiver_c,$receiver_d);
            $return_address = $this->get_address($region_list);
            $receiver_address = $return_address.$receiver_address;

            $receiver_phone = isset($post['receiver_phone'])?$post['receiver_phone']:'';
            if(empty($receiver_phone)){$this->error("请填写收件人电话");}
        }

        $submitter = isset($post['submitter'])?$post['submitter']:'';
        if(empty($submitter)){$this->error("请输入申请人姓名");}

        $submitter_company = isset($post['submitter_company'])?$post['submitter_company']:'';
        if(empty($submitter_company)){$this->error("请输入申请单位");}

        /*获取项目等待受理天数*/
        $return = M("project")->where(array("id"=>$p_id))->getField("wait_day");
        $wait_day = $return?$return:10;

        if($_FILES){
            $path = "/Uploads/Attachment/" . date("Y-m-d") . "/";
            $path = $this->upload_file($_FILES,$path);
        }else{
            $this->error("请先选择附件上传");
        }


        $data = array(
            'number' => date("YmdHis",time()).mt_rand(1000, 9999),
            'p_id' => $p_id,
            'apply_name' => $apply_name,
            'path' => $path,
            'is_deliver' => $is_deliver,
            'tracking_no' => $tracking_no,
            'company_name' => $company_name,
            'depart_name' => $depart_name,
            'contact' => $contact,
            'position_name' => $position_name,
            'contact_phone' => $contact_phone,
            'contact_address' => $contact_address,
            'need_survey' => $need_survey,
            'survey_time' => $survey_time,
            'survey_address' => $survey_address,
            'survey_contact' => $survey_contact,
            'survey_attention' => $survey_attention,
            'need_deliver' => $need_deliver,
            'receiver_name' => $receiver_name,
            'receiver_address' => $receiver_address,
            'receiver_phone' => $receiver_phone,
            'submitter' => $submitter,
            'submitter_company' => $submitter_company,
            'validate_phone' => $validate_phone,
            'operator_1' => 0,
            'refuse_reason' => '',
            'depart_id' => 0,
            'operator_2' => 0,
            'leader_comment' => '',
            'collect_opinion' => '',
            'apply_time' => time(),
            'wait_accept_time' => date("Y-m-d",strtotime("+$wait_day day")),
            'accept_time' => 0,
            'wait_complete_time' => 0,
            'complete_time' => 0,
            'status' => 1,//1-待受理
        );

        $res = M("apply")->add($data);
        if($res){
            $this->success($res);
        }else{
            $this->error("提交失败");
        }
    }

    /**补充申请
     * @author leiying
     */
    public function ApplyEdit(){

        $post = I('post.');

        $apply_id = isset($post["apply_id"])?$post["apply_id"]:0;
        $number = isset($post["number"])?$post["number"]:'';
        if(empty($apply_id) || empty($number)){
            $this->error("异常操作");
        }
        $validate_phone = trim($post["validate_phone"]);
        if(empty($validate_phone)){
            $this->error("请输入手机号码");
        }else{
            if(!$this->check_phone($validate_phone)){
                $this->error("手机号码有误，请重填");
            }
        }

        $validate_code = trim($post["validate_code"]);
        /*验证短信*/
        $res_record = M("validate_record")->where(array("record_key"=>$validate_phone,"record_type"=>'send_apply'))->getField("record_code");

        if(!empty($res_record)){
            if($res_record != $validate_code){
                $this->error("短信验证码不正确");
            }
        }else{
            $this->error("验证码信息不存在");
        }

        $p_id = isset($post['p_id'])?$post['p_id']:0;
        if(empty($p_id)){$this->error("请选择项目");}

        $is_deliver = isset($post["is_deliver"])?(int)$post["is_deliver"]:0;
        if(empty($is_deliver) || !in_array($is_deliver,array(1,2))){$this->error("请选择材料寄送");}

        $tracking_no = '';
        if($is_deliver == 1){//已经寄送
            $tracking_no = isset($post['tracking_no'])?$post['tracking_no']:'';
            if(empty($tracking_no)){$this->error("请填写快递单号");}
        }

        $depart_name = isset($post['depart_name'])?$post['depart_name']:'';
        if(empty($depart_name)){$this->error("请填写部门职务");}

        $contact = isset($post["contact"])?$post["contact"]:'';
        if(empty($contact)){$this->error("请填写联系人（主审单位）");}

        $contact_phone = isset($post['contact_phone'])?$post['contact_phone']:'';
        if(empty($contact_phone)){$this->error("请填写电话号码（主审单位）");}

        $contact_address = isset($post['contact_address'])?$post['contact_address']:'';
        if(empty($contact_address)){$this->error("请填写地址（主审单位）");}


        $need_survey = isset($post['need_survey'])?(int)$post['need_survey']:0;
        if(empty($need_survey) || !in_array($need_survey,array(1,2))){$this->error("请选择是否现场勘测");}
        $survey_start_time = '';
        $survey_end_time = '';
        $survey_address = '';
        $survey_contact = '';
        $survey_attention = '';
        if($need_survey == 1){
            $survey_start_time = isset($post['survey_start_time'])?$post['survey_start_time']:"";
            $survey_end_time = isset($post['survey_end_time'])?$post['survey_end_time']:"";
            if(empty($survey_start_time) || empty($survey_end_time)){$this->error("请选择现场勘测时间段");}
            $survey_address = isset($post['survey_address'])?$post['survey_address']:'';
            if(empty($survey_address)){$this->error("请填写地址（现场勘测）");}
            $survey_contact = isset($post['survey_contact'])?$post['survey_contact']:'';
            if(empty($survey_contact)){$this->error("请填写联系人（现场勘测）");}
            $survey_attention = isset($post['survey_attention'])?$post['survey_attention']:'';
            if(empty($survey_attention)){$this->error("请填写注意事项（现场勘测）");}
        }

        $need_deliver = isset($post['need_deliver'])?(int)$post['need_deliver']:0;
        if(empty($need_deliver) || !in_array($need_deliver,array(1,2))){$this->error("请选择是否需寄送审批表格");}

        $receiver_name = '';
        $receiver_address = '';
        $receiver_phone = '';
        if($need_deliver == 1){
            $receiver_name = isset($post['receiver_name'])?$post['receiver_name']:'';
            if(empty($receiver_name)){$this->error("请填写收件人姓名");}
            $receiver_address = isset($post['receiver_address'])?$post['receiver_address']:'';
            if(empty($receiver_address)){$this->error("请填写地址（寄送审批表格）");}
            $receiver_phone = isset($post['receiver_phone'])?$post['receiver_phone']:'';
            if(empty($receiver_phone)){$this->error("请填写收件人电话");}
        }

        $submitter = isset($post['submitter'])?$post['submitter']:'';
        if(empty($submitter)){$this->error("请输入申请人姓名");}

        $submitter_company = isset($post['submitter_company'])?$post['submitter_company']:'';
        if(empty($submitter_company)){$this->error("请输入申请单位");}

        /*获取项目等待受理天数*/
        $return = M("project")->where(array("id"=>$p_id))->getField("wait_day");
        $wait_day = $return?$return:10;

//        if($_FILES){
//            $path = "/Uploads/Attachment/" . date("Y-m-d") . "/";
//            $path = $this->upload_file($_FILES,$path);
//        }else{
//            $this->error("请先选择附件上传");
//        }


        $data = array(
            'p_id' => $p_id,
//            'path' => $path,
            'is_deliver' => $is_deliver,
            'tracking_no' => $tracking_no,
            'depart_name' => $depart_name,
            'contact' => $contact,
            'contact_phone' => $contact_phone,
            'contact_address' => $contact_address,
            'need_survey' => $need_survey,
            'survey_start_time' => $survey_start_time,
            'survey_end_time' => $survey_end_time,
            'survey_address' => $survey_address,
            'survey_contact' => $survey_contact,
            'survey_attention' => $survey_attention,
            'need_deliver' => $need_deliver,
            'receiver_name' => $receiver_name,
            'receiver_address' => $receiver_address,
            'receiver_phone' => $receiver_phone,
            'submitter' => $submitter,
            'submitter_company' => $submitter_company,
            'validate_phone' => $validate_phone,
            'operator_1' => 0,
            'refuse_reason' => '',
            'depart_id' => 0,
            'operator_2' => 0,
            'leader_comment' => '',
            'collect_opinion' => '',
            'apply_time' => time(),
            'wait_accept_time' => date("Y-m-d",strtotime("+$wait_day day")),
            'accept_time' => 0,
            'wait_complete_time' => 0,
            'complete_time' => 0,
            'status' => 1,//1-待受理
        );
        $res = M("apply")->where(array("id"=>$apply_id,"number"=>$number))->save($data);
        if($res){
            $this->success($apply_id);
        }else{
            $this->error("提交失败");
        }
    }

    /**取消被拒申请
     * @author leiying
     */
    public function cancelApply(){
        if(IS_POST){
            $id = I('post.apply_id',0);
            if(empty($id)){$this->error("数据缺失，如有疑问请联系客服");}
            $res = M("apply")->where(array("id"=>$id,"status"=>6))->save(array("status"=>7,"cancel_time"=>time()));
            if($res === false){
                $this->error("取消申请失败");
            }else{
                $this->success("取消申请成功");
            }
        }else{
            $this->error('非法操作，如有疑问请联系客服',U('Home/Index/apply_for'),3);
        }
    }

    /**
     * @param $arr
     * @return string
     * @author leiying
     */
    protected function get_address($arr){
        //查询选择的收货地址
        $res = M("region")->field("group_concat(fullName  SEPARATOR '') address")->where(array("code"=>array("in",$arr)))->find();
        return $res?$res['address']:'';
    }

    /**验证手机号
     * @param $phone
     * @return bool
     * @author leiying
     */
    protected function check_phone($phone){
        if(preg_match("/^1[34578]{1}\d{9}$/",$phone)){
            return true;
        }else{
            return false;
        }
    }

    /**上传资源文件
     * @param $files
     * @param $path  尾部加上"/"
     * @return string  返回存入数据表的路径
     * @author leiying
     */
    protected function upload_file($files,$path,$file_name = 'upfile'){
        $uptypes=array(//word excel pdf jpg png rar zip
            'application/vnd.ms-excel',//xls
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',//xlsx
            'application/msword',//doc
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document',//docx
            'application/x-zip-compressed',//zip
            'application/octet-stream',//rar
            'application/pdf',//pdf
            'image/jpg', 'image/jpeg', 'image/png', 'image/pjpeg', 'image/gif', 'image/bmp', 'image/x-png'
        );//上传文件类型列表
        $max_file_size = 200*1024*1024;     //上传文件大小限制, 单位BYTE
        $destination_folder=$_SERVER['DOCUMENT_ROOT'].$path; //上传文件路径
        if (!is_uploaded_file($files[$file_name]["tmp_name"])){   //防止脚本欺骗
            $this->error('图片不存在');
        }

        $file = $files["upfile"];
        if($max_file_size < $file["size"]){   //检查文件大小
            $this->error('文件太大');
        }

        if(!in_array($file["type"], $uptypes)){   //检查文件类型
            $this->error("文件类型不符!".$file["type"]);
        }

        if(!file_exists($destination_folder))
        {
            mkdir($destination_folder,0777,true);
        }

        $filename=$file["tmp_name"];
//        $image_size = getimagesize($filename);
        $pinfo=pathinfo($file["name"]);
        $ftype=$pinfo['extension'];
        $destination = $destination_folder.md5(time().mt_rand(1000, 9999)).".".$ftype;
        if (file_exists($destination))
        {
            $this->error("同名文件已经存在了");
        }

        if(!move_uploaded_file ($filename, $destination))
        {
            $this->error($filename."移动到".$destination."出错");
        }

        $pinfo=pathinfo($destination);
        $fname=$pinfo["basename"];
        return $path.$fname;
    }

}